<script setup lang="ts">
// 类型导入
import type {
  ProblemSubmitVO,
  RPageSafeProblemVo,
  ProblemSubmitQueryRequest,
  ProblemQueryRequest,
  ProblemVo,
} from '/@/api/openapi'

// 服务导入
import { ProblemControllerService } from '/@/api/openapi'

// UI组件导入
import { ElInput, ElTable, ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import moment from 'moment'

// 常量定义
const tagColors = ['tag-blue', 'tag-green', 'tag-orange'] as const
const DEFAULT_PAGE_SIZES = [8, 16, 32, 50] as const

// 状态管理
const loading = ref<boolean>(true)
const tableData = ref<ProblemVo[]>([])
const total = ref<number>(0)
const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

// 搜索参数
const searchParams = reactive({
  id: 0,
  tags: [] as string[],
  difficulty: '',
  pageSize: 8,
  pageNum: 1,
  title: '',
  sortField: 'create_time',
  sortOrder: 'descend',
})

// 工具函数
const formatNumber = (src: number, pos: number = 2): string => {
  const data = Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos)
  return data.toFixed(pos)
}

// 数据加载
const loadData = async () => {
  try {
    loading.value = true
    const res = await ProblemControllerService.listProblemVoByPage(searchParams)

    if (res.code === 200 && res.data) {
      tableData.value = res.data.records
      searchParams.pageNum = res.data.current
      searchParams.pageSize = res.data.size
      total.value = res.data.total
    } else {
      tableData.value = []
      ElMessage.error(res.message || '加载失败')
    }
  } catch (error) {
    ElMessage.error('加载失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 标签相关
const handleTagInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value?.input?.focus()
  })
}

const handleTagConfirm = () => {
  if (inputValue.value.trim()) {
    searchParams.tags.push(inputValue.value.trim())
    doSearch()
  }
  inputVisible.value = false
  inputValue.value = ''
}

const handleTagClose = (tag: string) => {
  const index = searchParams.tags.indexOf(tag)
  if (index > -1) {
    searchParams.tags.splice(index, 1)
    doSearch()
  }
}

// 搜索相关
const doSearch = () => {
  searchParams.pageNum = 1
  loadData()
}

const resetSearch = () => {
  Object.assign(searchParams, {
    title: '',
    difficulty: '',
    tags: [],
    pageNum: 1,
  })
  loadData()
}

// 分页相关
const handleSizeChange = (val: number) => {
  searchParams.pageSize = val
  doSearch()
}

const handleCurrentChange = (val: number) => {
  searchParams.pageNum = val
  loadData()
}

// 路由相关
const router = useRouter()
const toQuestionPage = (problem: ProblemVo) => {
  router.push(`/home/oj/problemSubmit/${problem.id}`)
}

// 生命周期
onMounted(() => {
  loadData()
})

const radioChange = (difficulty: string) => {
  console.log("选择了难度")
  console.log(difficulty)
  searchParams.difficulty = difficulty
}
</script>

<template>
  <div class="app-container">
    <el-card class="table-main" v-loading="loading">
      <!-- 标题区域 -->
      <div class="card-header">
        <h2 class="header-title">题目列表</h2>
        <el-tooltip content="刷新数据" placement="left">
          <el-button
            type="primary"
            :icon="Refresh"
            circle
            @click="loadData"
            :loading="loading"
          />
        </el-tooltip>
      </div>

      <!-- 搜索表单 -->
      <el-form class="search-form" :model="searchParams">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="题目">
              <el-input
                v-model="searchParams.title"
                placeholder="请输入题目关键词"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="题目难度" prop="difficulty">
              <el-select
                v-model="searchParams.difficulty"
                @change="radioChange"
                placeholder="请选择题目难度，默认全部"
                clearable
              >
                <el-option label="全部" value="" />
                <el-option label="简单" value="简单" />
                <el-option label="中等" value="中等" />
                <el-option label="困难" value="困难" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" @click="doSearch">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="标签" class="form-tag">
          <div class="tags-container">
            <span
              v-for="tag in searchParams.tags"
              :key="tag"
              class="custom-tag"
            >
              {{ tag }}
              <span class="tag-close" @click="handleClose(tag)">×</span>
            </span>
            <div v-if="inputVisible" class="tag-input-wrapper">
              <input
                ref="InputRef"
                v-model="inputValue"
                class="tag-input"
                type="text"
                @keyup.enter="handleInputConfirm"
                @blur="handleInputConfirm"
              />
            </div>
            <button v-else class="add-tag-btn" @click="showInput">
              <i class="fa fa-plus"></i>
              添加标签
            </button>
          </div>
        </el-form-item>
      </el-form>

      <el-divider />

      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          stripe
          highlight-current-row
          :empty-text="loading ? '加载中...' : '暂无数据'"
        >
          <el-table-column prop="id" label="题号" width="100" align="center" />
          <el-table-column prop="title" label="题目名称" align="center" />
          <el-table-column prop="difficult" label="题目难度" align="center">
            <template #default="scope">
              <el-tag
                v-if="scope.row.difficulty === '简单'"
                type="success"
                effect="dark"
                >{{ scope.row.difficulty }}
              </el-tag>
              <el-tag
                v-else-if="scope.row.difficulty === '中等'"
                type="info"
                effect="dark"
              >
                {{ scope.row.difficulty }}
              </el-tag>
              <el-tag v-else type="danger" effect="dark"
                >{{ scope.row.difficulty }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="通过率" align="center">
            <template #default="scope">
              {{
                `${
                  scope.row.submitNum
                    ? formatNumber(
                        scope.row.acceptedNum / scope.row.submitNum,
                        2,
                      )
                    : '0'
                }% (${scope.row.acceptedNum}/${scope.row.submitNum})`
              }}
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间">
            <template #default="scope">
              {{ moment(scope.row.createTime).format('YYYY-MM-DD') }}
            </template>
          </el-table-column>

          <el-table-column prop="tags" label="标签" align="center">
            <template #default="scope">
              <div class="tags-group">
                <span
                  v-for="(tag, index) in scope.row.tags.slice(0, 3)"
                  :key="tag"
                  class="custom-tag"
                  :class="tagColors[index % tagColors.length]"
                >
                  {{ tag }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="150"
            align="center"
          >
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="toQuestionPage(scope.row)"
                >查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pager-wrapper">
        <el-pagination
          v-model:current-page="searchParams.pageNum"
          v-model:page-size="searchParams.pageSize"
          :page-sizes="DEFAULT_PAGE_SIZES"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
// 布局相关
.app-container {
  padding: 20px;
}

.table-main {
  max-width: 1400px;
  margin: 0 auto;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

// 头部样式
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.header-title {
  font-size: 20px;
  font-weight: 500;
  color: #1f2329;
  margin: 0;
}

// 搜索表单
.search-form {
  background: #f8f9fa;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 24px;
}

.table-wrapper {
  margin: 20px 0;

  .el-table {
    border-radius: 8px;
    overflow: hidden;
  }
}

.pager-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.tag {
  margin-right: 10px;
  margin-bottom: 5px;
}

.inputVisible {
  margin-top: 10px;
  width: 100px;
}

// 优化表单布局
.el-form-item {
  margin-bottom: 0;

  .el-input,
  .el-select {
    width: 100%;
  }
}

// 优化按钮组样式
.el-form-item:last-child {
  .el-form-item__content {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
  }
}

// 标签输入框样式优化
.form-tag {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  margin-top: 16px;

  .el-tag {
    margin: 0;
  }
}

// 响应式优化
@media (max-width: 768px) {
  .table-main {
    width: 95%;
    padding: 10px;
  }

  .search-form {
    padding: 15px;
  }

  .el-form-item:last-child {
    margin-top: 10px;
  }
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  min-height: 32px;
  padding: 4px 0;
}

.custom-tag {
  display: inline-flex;
  align-items: center;
  padding: 4px 8px;
  font-size: 13px;
  line-height: 1.4;
  background: #f0f2f5;
  color: #666;
  border-radius: 4px;
  transition: all 0.2s;

  &:hover {
    background: #e6e8eb;
  }

  .tag-close {
    margin-left: 4px;
    font-size: 14px;
    width: 16px;
    height: 16px;
    line-height: 14px;
    text-align: center;
    border-radius: 50%;
    cursor: pointer;

    &:hover {
      background: rgba(0, 0, 0, 0.1);
    }
  }
}

.tag-input-wrapper {
  display: inline-block;
}

.tag-input {
  width: 80px;
  padding: 4px 8px;
  font-size: 13px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
  transition: all 0.2s;

  &:focus {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }
}

.add-tag-btn {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  font-size: 13px;
  color: #666;
  background: none;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    color: #409eff;
    border-color: #409eff;
  }

  i {
    font-size: 12px;
  }
}

// 表格中的标签样式
.tags-group {
  display: flex;
  gap: 6px;
  justify-content: center;
  flex-wrap: wrap;
}

// 定义不同颜色的标签
.tag-blue {
  background-color: #e6f4ff;
  color: #1890ff;
}

.tag-green {
  background-color: #f6ffed;
  color: #52c41a;
}

.tag-orange {
  background-color: #fff7e6;
  color: #fa8c16;
}

// 响应式调整
@media (max-width: 768px) {
  .form-tag {
    margin-top: 20px;
  }

  .tags-container {
    flex-direction: column;
    align-items: flex-start;
    padding: 8px 0;
  }

  .tag-input {
    width: 100%;
  }

  .add-tag-btn {
    width: 100%;
    justify-content: center;
  }
}
</style>
